import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';
import Toast from '@vant/weapp/toast/toast';

Page({
  data: {
    defaultData: {
      title: "订单验收", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    currentImageUrl: '/images/image-quick/dropDown.png', //下拉箭头
    radio: '',
    value: "",
    checked: [], //折叠面板被选中的选项
    order: null,
    roomList: [],
    currentRoomId: null, //被选中的房间id
    expandedProducts: {},
    isAllExpanded: false, // 用于记录是否全部展开 
  },
  onLoad(options) {
    if (options.order) {
      const order = JSON.parse(decodeURIComponent(options.order));
      console.log("order.rooms", order);
      this.setData({
        order: order,
        roomList: order.rooms
      })
    }
    console.log("roomList", this.data.roomList);
    if (this.data.roomList.length > 0) {
      this.setData({
        currentRoomId: this.data.roomList[0].orderRoomId // 默认选中第一个房间
      });
    }
    // 为折叠面板每一组选择项添加checked
    this.data.roomList.forEach(room => {
      room.children.forEach(product => {
        product.acceptanceType.items.forEach(citemsList => {
          citemsList.items.forEach(citems => {
            citems.checked = [];
          });
        });
      });
    });
    // 为商品选择项添加radio
    this.data.roomList.forEach(room => {
      room.children.forEach(product => {
        product.radio = "";
      });
    });
    // 更新数据
    this.setData({
      roomList: this.data.roomList
    });
    console.log("this.data.roomList", this.data.roomList);
  },

  // 商品的状态
  onChangeRadio(event) {
    const {
      productid
    } = event.currentTarget.dataset;
    const {
      roomList
    } = this.data;
  
    // 找到对应的产品
    const product = roomList.reduce((foundProduct, room) => {
      if (foundProduct) return foundProduct;
      return room.children.find(p => p.productId === productid);
    }, null);
  
    // 更新产品的radio属性
    if (product) {
      product.radio = event.detail;
  
      // 根据 radio 的值更新 checked 数组
      product.acceptanceType.items.forEach(citemsList => {
        citemsList.items.forEach(citems => {
          let valItems = [];
          if (event.detail === "1") {
            valItems = citems.items.filter(subitem => subitem.val == "1");
          } else if (event.detail === "2") {
            valItems = citems.items.filter(subitem => subitem.val == "0");
          }
          const valIds = valItems.map(item => String(item.id));
          citems.checked = valIds;
        });
      });
  
      this.setData({
        roomList: this.data.roomList
      });
      console.log("roomList updated:", this.data.roomList);
    }
  },
  

  //折叠面板的选中和不选中
  onChangeCheckbox(event) {
    console.log("event", event);
    const {
      citemsid,
      citemslistid,
      productid,
      subitemid,
      val
    } = event.currentTarget.dataset;
    console.log("subitemid", subitemid);
    const {
      roomList,
    } = this.data;

    // 找到对应的产品和检测项
    const currentRoomId = this.data.currentRoomId;
    const room = roomList.find(room => room.orderRoomId == currentRoomId);
    const product = room.children.find(product => product.productId == productid);
    const citemsList = product.acceptanceType.items.find(citemsList => citemsList.id == citemslistid);
    const citems = citemsList.items.find(citems => citems.id == citemsid);
    const subitem = citems.items.find(subitem => subitem.id == subitemid);

    // 查找 citems 中 val 为 1 的选项
    const val1Item = citems.items.find(item => item.val == "1");
    const val1Id = val1Item ? val1Item.id : null;

    const subitemidStr = String(subitemid);
    const val1IdStr = String(val1Id);

    if (citems.checked.length == 0) {
      citems.checked = event.detail;
    } else {
      if (subitem.val == "0") {
        if (event.detail.includes(val1IdStr)) {
          citems.checked = [subitemidStr];
        } else {
          if (citems.checked.includes(subitemidStr)) {
            citems.checked = citems.checked.filter(id => id !== subitemidStr);
          } else {
            citems.checked = [...citems.checked, subitemidStr];
          }
        }
      } else if (subitem.val == "1") {
        if (citems.checked.includes(val1IdStr)) {
          citems.checked = [];
        } else {
          citems.checked = [subitemidStr];
        }
      }
    }

    // 检查是否所有的 checked 里面的id所对应的选项的 val 为 1
    let allVal1 = true;
    let hasVal0 = false; // 是否存在 val 为 0 的选项

    for (let citemsList of product.acceptanceType.items) {
      for (let citems of citemsList.items) {
        if (citems.checked.length === 0) {
          allVal1 = false;
          hasVal0 = false;
          break;
        }
        for (let id of citems.checked) {
          const subitem = citems.items.find(item => item.id == id); // 使用 == 进行类型转换比较
          if (subitem.val == "0") {
            hasVal0 = true;
            allVal1 = false;
            break;
          }
        }
        if (hasVal0) break; // 如果找到了val为0的项，直接跳出循环
      }
      if (hasVal0) break; // 如果找到了val为0的项，直接跳出循环
    }

    // 更新 radio 的状态
    if (allVal1 && !hasVal0) {
      product.radio = "1";
    } else if (hasVal0) {
      product.radio = "2";
    } else {
      product.radio = "0"; // 默认值
    }

    // 更新 roomList
    this.setData({
      roomList: this.data.roomList
    });
    console.log("roomLists", this.data.roomList);
    console.log("product.acceptanceType.items", product.acceptanceType.items);
  },


  // 房间切换
  handleTabClick(e) {
    const roomId = e.currentTarget.dataset.roomId;
    this.setData({
      currentRoomId: roomId
    });
  },

  //单个折叠面板
  handleDropDown(event) {
    const productId = event.currentTarget.dataset.productid;
    console.log("productId", productId);
    this.setData({
      [`expandedProducts.${productId}`]: !this.data.expandedProducts[productId]
    });
    console.log("expandedProducts", this.data.expandedProducts);
    this.checkAllExpanded();
  },
  //检查用户有没有手动全部展开或全部折叠
  checkAllExpanded() {
    let allExpanded = true;
    let allCollapsed = true;
    this.data.roomList.forEach(room => {
      room.children.forEach(product => {
        if (this.data.expandedProducts[product.productId]) {
          allCollapsed = false;
        } else {
          allExpanded = false;
        }
      });
    });
    if (allExpanded) {
      this.setData({
        isAllExpanded: true
      });
    } else if (allCollapsed) {
      this.setData({
        isAllExpanded: false
      });
    }
  },
  //全部折叠和全部展开
  toggleExpandAll() {
    const isAllExpanded = !this.data.isAllExpanded;
    const expandedProducts = {};
    console.log(this.data.roomList);
    this.data.roomList.forEach(room => {
      console.log("roomListroom", room);
      room.children.forEach(product => {
        expandedProducts[product.productId] = isAllExpanded;
      });
    });
    this.setData({
      expandedProducts,
      isAllExpanded
    });
  },

  // 一键正常验收
  // 一键正常验收
allOptions() {
  const {
    currentRoomId,
    roomList
  } = this.data;

  const currentRoom = roomList.find(room => room.orderRoomId === currentRoomId);

  currentRoom.children = currentRoom.children.map(product => {
    product.radio = "1";

    // 将所有 subitem.val == "1" 的选项的 id 放到各自的 checked 里面
    product.acceptanceType.items.forEach(citemsList => {
      citemsList.items.forEach(citems => {
        const val1Items = citems.items.filter(subitem => subitem.val == "1");
        const val1Ids = val1Items.map(item => String(item.id));
        citems.checked = val1Ids;
      });
    });

    return product;
  });

  this.setData({
    roomList
  });
  console.log("一键验收", currentRoom);
},


  // 清除选项
  clearOptions() {
    const {
      currentRoomId,
      roomList
    } = this.data;  
    const currentRoom = roomList.find(room => room.orderRoomId === currentRoomId);
    currentRoom.children = currentRoom.children.map(product => {
      product.radio = "";
      // 将所有 checked 数组清空
      product.acceptanceType.items.forEach(citemsList => {
        citemsList.items.forEach(citems => {
          citems.checked = [];
        });
      });
      return product;
    });
    this.setData({
      roomList
    });
    console.log("清除选项", currentRoom);
  },
  
  handleDropDown(event) {
    const productId = event.currentTarget.dataset.productid;
    this.setData({
      [`expandedProducts.${productId}`]: !this.data.expandedProducts[productId]
    });
  },

  //验收订单
  async clickOrederEnd() {
    const reqTemplate = {
      orderId: this.data.order.orderId
    }
    try {
      const res = await request({
        url: indexApi.orederEnd(),
        method: "POST",
        data: reqTemplate
      });
      console.log(res);
      wx.switchTab({
        url: '/pages/order/index',
      })
    } catch (error) {
      console.error("Error:", error);
    }
  },


  backOrder() {
    wx.navigateBack({
      delta: 1
    });
  },

  //上传图片
  afterRead(event) {
    const {
      file
    } = event.detail;
    this.uploadFile(file);
  },

  // 文件超出大小限制处理函数
  onOversize(event) {
    wx.showToast({
      title: '文件大小超出限制',
      icon: 'none'
    });
  },

  // 上传图片
  async uploadFile(file) {
    try {
      const uploadTask = wx.uploadFile({
        url: indexApi.upLoadApi(),
        header: {
          "Content-Type": "multipart/form-data"
        },
        filePath: file.url,
        name: 'file',
        formData: {

        },
        success: (res) => {
          const data = JSON.parse(res.data);
          console.log('Upload success', data);
          this.setData({
            fileList: [...this.data.fileList, file]
          });
          console.log("fileList", this.data.fileList);

        },
        fail: (err) => {
          console.error('Upload failed', err);
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      });
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 删除图片
  onDelete(event) {
    const {
      index
    } = event.detail;
    const {
      fileList
    } = this.data;
    console.log("event.detail", event.detail);
    console.log("fileList", this.data.fileList);
    fileList.splice(index, 1); // 删除对应索引的文件
    this.setData({
      fileList
    });

  },

})